package com.facedemo.db.utils;

import com.facedemo.db.PersonFeatureDao;
import com.facedemo.db.entity.PersonFeature;
import com.facedemo.utils.LogUtils;

import java.io.File;
import java.util.List;

public class PersonFeatureDaoUtils {
    /**
     * 加载所有人脸
     * @return List<PersonFeature>
     * */
    public static List<PersonFeature> loadAll() {
        List<PersonFeature> list = DaoManager.getInstance().getDaoSession().getPersonFeatureDao().loadAll();
        LogUtils.printD("DAO 加载所有人脸,数量："+list.size());
        return list;
    }

    /**
     *  删除人脸，通过人员ID
     * @param person_id 人员Id
     * @param deletePic 是否同时删除人脸图片
     *  */
    public static void deleteByPersonId(String person_id,boolean deletePic) {
        if(person_id==null || person_id.length()==0) return;
        LogUtils.printD("DAO 删除人脸=："+person_id);

        List<PersonFeature> list = queryByPersonId(person_id);
        if(list!=null) {
            for(PersonFeature pf:list) {
                if(deletePic) {//同时删除人脸图片
                    String pisPath = pf.getFacePicPath();
                    if(pisPath!=null && pisPath.length()!=0 && !pisPath.equals("null")) {
                        File file = new File(pisPath);
                        if(file.exists()) {
                            LogUtils.printD("DAO 删除图片=："+pisPath);
                            file.delete();
                        }
                    }
                }
                DaoManager.getInstance().getDaoSession().getPersonFeatureDao().delete(pf);
            }
        }
    }

    /**
     * 删除所有人脸
     * */
    public static void deleteAll() {
        LogUtils.printD("DAO 删除所有人脸");
        DaoManager.getInstance().getDaoSession().getPersonFeatureDao().deleteAll();
    }

    /**
     *  保存人脸信息，存在则更新，不存在则插入
     *  以 人员ID和人脸ID作为复合主键
     * @param pf PersonFeature
     *  */
    public static void addOrUpdate(PersonFeature pf) {
        if(pf==null) return;
        LogUtils.printD("DAO 保存人脸到数据库："+pf.getPersonId()+" "+pf.getFaceId());
        DaoManager.getInstance().getDaoSession().getPersonFeatureDao().insertOrReplace(pf);
    }

    /**
     * 查询人脸，通过人员ID
     * @param person_id
     * @return List<PersonFeature>
     */
    public static List<PersonFeature> queryByPersonId(String person_id) {
        if(person_id==null || person_id.length()==0) return null;
        LogUtils.printD("查询人脸："+person_id);

        List<PersonFeature> results = DaoManager.getInstance().getDaoSession().getPersonFeatureDao().queryBuilder()
                .where(PersonFeatureDao.Properties.PersonId.eq(person_id))
                .list();
        return results;
    }

    /**
     * 查询总人脸数
     * */
    public static long getTotalNum() {
        long num = DaoManager.getInstance().getDaoSession().getPersonFeatureDao().count();
        LogUtils.printD("DAO 查询人脸总数："+num);
        return num;
    }
}
